package com.rmv.ums.configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;

public class ConfigurationLoader {

	private static final Logger logger = Logger.getLogger(ConfigurationLoader.class);

	private URL url;
	private Properties configuration;

	public ConfigurationLoader(URL url) {
		this.url = url;
		load();
	}

	public URL getUrl() {
		return url;
	}

	public Properties getConfiguration() {
		return configuration;
	}

	private void load() {
		String path = url.getPath();
		if (logger.isDebugEnabled())
			logger.debug("loading configuration file from:" + path);
		InputStream is = null;
		try {
			is = new FileInputStream(url.getPath());
			configuration = new Properties();
			configuration.load(is);
			is.close();
		} catch (FileNotFoundException e) {
			throw new RuntimeException("error loading configuration file: file '" + path + "' doesn't exist", e);
		} catch (IOException e) {
			throw new RuntimeException("error loading configuration file: path=" + path, e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException ignored) {
					logger.error(ignored.getMessage(), ignored);
				}
			}
		}
	}

}
